using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Template
{
    [Serializable()]
    public class TemplateDetail : Csla.BusinessBase<TemplateDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _templateid = Guid.NewGuid();
        private string _templatename = string.Empty;
        private int _numberofplaceholders = 0;

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid templateid
        {
            get
            {
                CanReadProperty("templateid", true);
                return _templateid;
            }
            set
            {
                CanWriteProperty("templateid", true);
                if (!_templateid.Equals(value))
                {
                    _templateid = value;
                    PropertyHasChanged("templateid");
                }
            }
        }

        public string templatename
        {
            get
            {
                CanReadProperty("templatename", true);
                return _templatename;
            }
            set
            {
                CanWriteProperty("templatename", true);
                if (value == null)
                    value = string.Empty;
                if (!_templatename.Equals(value))
                {
                    _templatename = value;
                    PropertyHasChanged("templatename");
                }
            }
        }

        public int numberofplaceholders
        {
            get
            {
                CanReadProperty("numberofplaceholders", true);
                return _numberofplaceholders;
            }
            set
            {
                CanWriteProperty("numberofplaceholders", true);
                if (!_numberofplaceholders.Equals(value))
                {
                    _numberofplaceholders = value;
                    PropertyHasChanged("numberofplaceholders");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _templateid;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // templatename
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "templatename");
            ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("templatename", 500));
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in TemplateDetail
            //AuthorizationRules.AllowRead("templateid", "TemplateDetailReadGroup");
            //AuthorizationRules.AllowRead("templatename", "TemplateDetailReadGroup");
            //AuthorizationRules.AllowRead("numberofplaceholders", "TemplateDetailReadGroup");

            //AuthorizationRules.AllowWrite("templatename", "TemplateDetailWriteGroup");
            //AuthorizationRules.AllowWrite("numberofplaceholders", "TemplateDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in TemplateDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("TemplateDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in TemplateDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("TemplateDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in TemplateDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("TemplateDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in TemplateDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("TemplateDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private TemplateDetail()
        { /* require use of factory method */
        }

        public static TemplateDetail NewTemplateDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a TemplateDetail");
            return DataPortal.Create<TemplateDetail>();
        }

        public static TemplateDetail GetTemplateDetail(Guid templateid)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a TemplateDetail");
            return DataPortal.Fetch<TemplateDetail>(new Criteria(templateid));
        }

        public static void DeleteTemplateDetail(Guid templateid)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a TemplateDetail");
            DataPortal.Delete(new Criteria(templateid));
        }

        public override TemplateDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a TemplateDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a TemplateDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a TemplateDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid templateid;

            public Criteria(Guid templateid)
            {
                this.templateid = templateid;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@templateid", criteria.templateid);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetTemplateHeaderByTemplateID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            //_templateid = dr.GetGuid("templateid");
            _templatename = dr.GetString("templatename");
            _numberofplaceholders = dr.GetInt32("numberofplaceholders");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertTemplateHeader.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@templateid", _templateid);
            DAL.AddParameter("@templatename", _templatename);
            DAL.AddParameter("@numberofplaceholders", _numberofplaceholders);
            //cm.Parameters["@Newtemplateid"].Direction = ParameterDirection.Output;
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }

        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateTemplateHeader.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@templateid", _templateid);
            DAL.AddParameter("@templatename", _templatename);
            DAL.AddParameter("@numberofplaceholders", _numberofplaceholders);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_templateid));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteTemplateHeader.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@templateid", criteria.templateid);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
